package com.lilosoft.core.utils;

import com.alibaba.fastjson.JSON;
import com.lilosoft.core.exception.MyException;
import com.lilosoft.core.result.JsonResult;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 渲染工具类
 *
 * @author qiusheng
 * @Date 2018-10-30
 */
public class RenderUtil {
	
	/**
	 * 异常返回渲染
	 * @param response
	 * @param msg
	 */
	public static void renderError(HttpServletResponse response, String msg, Integer status) {
		JsonResult obj = new JsonResult();
		obj.setSuccess(false);
		obj.setStatus(status);
		obj.setMsg(msg);
        
		renderJson(response, obj);
	}

    /**
     * 渲染json对象
     */
    public static void renderJson(HttpServletResponse response, Object jsonObject) {
        try {
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, OPTIONS, DELETE, PATCH");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
            
            PrintWriter writer = response.getWriter();
            writer.write(JSON.toJSONString(jsonObject));
            writer.flush();
        } catch (IOException e) {
            throw new MyException("系统异常");
        }
    }
}
